/*
 * Copyright 2005-2013 finalist.cn. All rights reserved.
 * Support: http://www.finalist.cn
 * License: http://www.finalist.cn/license
 */
package com.finalist.dao.impl;

import java.util.List;

import javax.persistence.FlushModeType;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Repository;

import com.finalist.dao.AreaDao;
import com.finalist.entity.Area;

/**
 * Dao - 地区
 * 
 * @author Finalist IT Group
 * @version 3.0
 */
@Repository("areaDaoImpl")
public class AreaDaoImpl extends BaseDaoImpl<Area, Long> implements AreaDao
{

    public List<Area> findRoots(Integer count)
    {
        String jpql = "select area from Area area where area.parent is null order by area.order asc";
        TypedQuery<Area> query = entityManager.createQuery(jpql, Area.class).setFlushMode(FlushModeType.COMMIT);
        if (count != null)
        {
            query.setMaxResults(count);
        }
        return query.getResultList();
    }

    @Override
    public List<Area> findChildrens(Long parentId)
    {
        String jpql = "select area from Area area where area.parent.id = :parentId order by area.order asc";
        TypedQuery<Area> query = entityManager.createQuery(jpql, Area.class).setFlushMode(FlushModeType.COMMIT).setParameter("parentId", parentId);

        return query.getResultList();
    }

    @Override
    public Area findAreaById(Long id)
    {
        String jpql = "select area from Area area where area.id = :id";
        TypedQuery<Area> query = entityManager.createQuery(jpql, Area.class).setFlushMode(FlushModeType.COMMIT).setParameter("id", id);

        return query.getSingleResult();
    }

    @Override
    public Area findAreaByTreePathAndName(String treePath, String name)
    {
        String jpql = "select area from Area area where area.treePath = :treePath and area.name = :name";
        TypedQuery<Area> query = entityManager.createQuery(jpql, Area.class).setFlushMode(FlushModeType.COMMIT).setParameter("treePath", treePath).setParameter("name", name);
        return query.getSingleResult();
    }

}